#include <stdio.h>
#include <string.h>

int main(void)
{
	FILE *pFile, *pFileOut;
	char buffer[100] , cmd[100];
	int indbuf=0;
	//for test
	//const char *cmd_path = "/home/maikon/dropapp/cmd.txt";
	const char *cmd_path = "/home/maikon/Dropbox/Apps/scripts/cmd.txt";
	
	printf("------running----------\n");
	
	do
	{	
		pFile = fopen(cmd_path, "r");
		if(pFile == NULL) perror("Error opening file cmd.txt for r \n");
		else
		{
			//to read the entire file and saving at buffer
			while(!feof(pFile))
			{
				if(fgets(buffer, 100, pFile) == NULL)
				{
					break;
				}
				//fputs(buffer, stdout);	
			}
			fclose(pFile);	
			//the command was given , so run and return to 0 state				
			switch(buffer[0])
			{
				case '1':	
				    pFileOut = fopen(cmd_path, "w");
				    if(pFile == NULL) perror("1 Error opening file cmd.txt for w \n");
					for(indbuf=2; indbuf<= strlen(buffer); indbuf++)
					{
						cmd[indbuf-2] = buffer[indbuf];
					}
					system("fswebcam house2.jpg");
					system("cp house2.jpg /home/maikon/Dropbox/Apps/scripts");
					//system("cp house2.jpg /home/maikon/dropapp/scripts");		
					printf("%d \n", strlen(buffer));
					buffer[0] = '0';
					buffer[strlen(buffer)] = '\0';
					
					fwrite (buffer , sizeof(char), strlen(buffer), pFileOut);
					printf("%s \n",buffer);
					fclose(pFileOut);
				break;						
			}
			//this is for the second argument command
			switch(buffer[1])
			{
				case '1':
					pFileOut = fopen(cmd_path, "w");
				    if(pFile == NULL) perror("2 Error opening file cmd.txt for w \n");
					for(indbuf=2; indbuf<= strlen(buffer); indbuf++)
					{
						cmd[indbuf-2] = buffer[indbuf];
					}
					
					printf("1 1\n");
					system("ssh pi@192.168.0.114 'cd /home/pi/cprog/; ./relay1 0 1'");	
					
					buffer[1] = '2';
					buffer[strlen(buffer)] = '\0';
					fwrite (buffer , sizeof(char), strlen(buffer), pFileOut);
					printf("%s \n",buffer);
					fclose(pFileOut);
				break;
				case '0':
				    pFileOut = fopen(cmd_path, "w");
				    if(pFile == NULL) perror("3 Error opening file cmd.txt for w \n");
					for(indbuf=2; indbuf<= strlen(buffer); indbuf++)
					{
						cmd[indbuf-2] = buffer[indbuf];
					}
					printf("1 0\n");
					
					system("ssh pi@192.168.0.114 'cd /home/pi/cprog/; ./relay1 0 0'");
					buffer[1] = '2';
					
					buffer[strlen(buffer)] = '\0';
					fwrite (buffer , sizeof(char), strlen(buffer), pFileOut);
					printf("%s \n",buffer);
					fclose(pFileOut);
				break;
				case '2':
					
				break;
			}	
		}	
	} while(buffer[0] != '!');	
	printf("got to read ! \n");
	
	return 0;
}


